<?php

namespace app\order\logic;
use app\common\library\RedissLock;
use app\common\service\TiktokPackageApiService;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use app\customer\logic\TikMessageLogic;
use app\order\logic\OrderLogic;
use think\facade\Config;
use think\facade\Db;
use app\order\model\WebhooksModel;
use think\facade\Cache;
use app\api\logic\TrackLogic;
class OrderWebHookLogic extends BasicLogic
{




    /**
     * @desc     订单状态回调MQ消费方法
     * @atuthor  luckyXiong
     * @date     2024-03-22
     */
     public function orderStatusChange($info){

         htmlLog(['data'=>$info],OPERATE_LOG . date('Ym') . '/orderStatusChange/' . date('Ymd') . '.txt');
         //重复执行锁处理;
         $update_time= $info['data']['update_time']??'';


      /*   $redis_lock = new RedissLock();
         $key        = 'orderStatusChange_consumer:'.time();
         $lock       = $redis_lock::lock($key, $redis_lock::UNBLOCK, 100);
         if (!$lock) {
             return  ['code'=>201,'msg'=>'数据并发了'];
         }*/
         if(!$info)  return '';

         $type         = $info['type']??'';
         $tik_shop_id  = $info['shop_id']??'';
         $order_id     = $info['data']['order_id']??'';
         $order_status = $info['data']['order_status']??'';
         $config       = Config('Logisticskey.shop_id');
         $shop_id      = $config[$tik_shop_id]??'0';
         if($shop_id==13)  return  true;
         if($type==1){
             $insert_arr = [
                 'order_id'    =>$order_id,
                 'order_status'=>$order_status,
                 'type'        =>$type,
                 'shop_id'     =>$shop_id,
                 'post'        =>json_encode($info['data'],JSON_UNESCAPED_UNICODE),
                 'update_time' =>$update_time,
                 'created_time'=>date('Y-m-d H:i:s',time()),
             ];
             Db::name('webhooks')->insert($insert_arr);
             self::changeTypeOrder($info,$shop_id);
         }
        // $lock->unlock();
         return true;
     }



    /**
     * @desc   订单类型信息
     * @author luckyXiong
     * @date   2024-04-22  changeTypeRefund
     */
    public function changeTypeOrder($data,$shop_id){
        $order_status = $data['data']['order_status']??'';
        $order_id     = $data['data']['order_id']??'';
        $update_time  = $data['data']['update_time']??'';
        $OrderStatusChangeTimeKey = 'OrderStatusChangeTime::' . $order_id;
        if($order_status =='CANCEL'){
            $order_status = 'CANCELLED';
        }

        //缓存订单状态时间;防止取的状态是历史的
        $OrderStatusChangeTime = Cache::store('redis')->get($OrderStatusChangeTimeKey);
        if(!$OrderStatusChangeTime || $OrderStatusChangeTime<$update_time){
            $OrderStatusChangeTime = $update_time;
            Cache::store('redis')->set($OrderStatusChangeTimeKey, $OrderStatusChangeTime, 24 * 3600);
        }
        $order_info = Db::name('order')->where('order_id',$order_id)->field('id,shop_id,order_id,updatetime,tracking_number')->find();
        if($order_info){
            self::order_info_exist($order_info,$update_time,$OrderStatusChangeTime,$order_status);
        }else{
            self::order_info_not_exist($order_id,$shop_id);
        }
    }


    /**
     * @desc   订单退款信息
     * @author luckyXiong
     * @date   2024-04-29  changeTypeRefund
     */
    public function changeTypeRefund($info,$shop_id){
        if(!$info||!$shop_id)  return  true;
        $arr = [
            'order_id'            =>$info['data']['order_id']??'',
            'shop_id'             =>$shop_id,
            'reverse_event_type'  =>$info['data']['reverse_event_type']??'',
            'reverse_order_id'    =>$info['data']['reverse_order_id']??'',
            'reverse_order_status'=>$info['data']['reverse_order_status']??'',
            'reverse_type'        =>$info['data']['reverse_type']??'',
            'update_time'         =>$info['data']['update_time']??'',
            'timestamp'           =>$info['timestamp']??'',
            'created_time'        =>date('Y-m-d H:i:s',time()),
        ];
        Db::name('order_refund_webhook')->insert($arr);
    }



    /**
     * @desc   返回会话消ID
     * @author luckyXiong
     * @date   2024-04-29
     */
    public function changeTypeConversations($info,$shop_id){
        if(!$info||!$shop_id)  return  true;
        $time = $info['data']['create_time']??'';
        $arr = [
            'shop_id'        =>$shop_id,
            'conversation_id'=>$info['data']['conversation_id']??'',
            'created_time'   =>$time ? date("Y-m-d H:i:s", $time):'',
        ];
        $exist_info = Db::name('conversations_info')->where('conversation_id',$info['data']['conversation_id'])->find();
        if(!$exist_info){
            Db::name('conversations_info')->insert($arr);
        }
    }


    /**
     * @desc   返回会话ID消息
     * @author luckyXiong
     * @date   2024-04-29
     */
    public function changeTypeConversationsMessage($info,$shop_id){
        if(!$info||!$shop_id)  return  true;
        $content = $info['data']['content']??'';
        $content = json_decode($content,true);
        if(!$content)      return  true;
        $role  = $info['data']['sender']['role']??'';
        if($role=='ROBOT')  return  true;
        $type  = $info['data']['type']??'';
        if($type=='NOTIFICATION'){
            $type = 3;
        }elseif($type=='TEXT'){
            $type = 1;
        }else{
            $type = 2;
        }
        $arr = [
            'shop_id'        =>$shop_id,
            'conversation_id'=>$info['data']['conversation_id']??'',
            'content'        =>$content['content']??'',
            'message_id'     =>$info['data']['message_id']??'',
            'is_visible'     =>$info['data']['is_visible']? 1 : 2,
            'sender_im_id'   =>$info['data']['sender']['im_user_id']??'',
            'sender_role'    =>$info['data']['sender']['role']??'',
            'sender_mess_type' =>$type,
            'createtime'       =>$info['timestamp']??'',
        ];
        if($arr['sender_role']=='BUYER' && $type==2)  return true;
        Db::name('conversations_message_log')->insert($arr);
    }



    /**
     * @desc   老系统面单同步临时使用
     * @author luckyXiong
     * @date   2024-05-08
     */
    public function documentsUrl($info=[]){
        htmlLog(['data'=>$info],OPERATE_LOG . date('Ym') . '/documentsUrl/' . date('Ymd') . '.txt');
        if(!$info) return '';
        $order_id = $info['order_id']??'';
        $url      = $info['pdf_url']??'';
        Db::name('order')->where('order_id',$order_id)->update(['shipping_documents'=>$url,'shipping_documents_status'=>4]);
        return 1;
    }





    /**
     * @desc 订单存在时
     * @author luckyXiong
     * @date 2024-03-22
     */
    public function order_info_exist($order_info,$update_time,$OrderStatusChangeTime,$order_status){
        htmlLog(['order_info'=>$order_info,'update_time'=>$update_time,'OrderStatusChangeTime'=>$OrderStatusChangeTime,'order_status'=>$order_status],OPERATE_LOG . date('Ym') . '/order_info_exist/' . date('Ymd') . '.txt');
        if ($OrderStatusChangeTime <= $update_time) {
            Db::name('order')->where('id',$order_info['id'])->update(['status'=>$order_status]);
        }
        $order_ship_status = Db::name('order_ship')->where(['order_id'=>$order_info['order_id']])->value('status');
        //状态关联发货状态
        if($order_ship_status && $order_ship_status == 2  && $order_status !== "AWAITING_SHIPMENT"){
            Db::name('order_ship')->where('order_id',$order_info['order_id'])->update(['status'=>5]);
        }

        if($order_status == "CANCELLED"){
            //关闭订单
            Db::name('order_ship')->where('order_id',$order_info['order_id'])->update(['msg'=>"订单已关闭，中断系统发货流程",'status'=>5]);
        }

        //update  2024-05-13 当订单状态为待揽收时,获取跟踪号并更新订单
        if($order_status == "AWAITING_COLLECTION"){
            //todo 推送队列执行 获取运单号
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_UPDATE_TRACK_NUMBER_QUEUE,
                ['order_id'=>$order_info['order_id'],'shop_id'=>$order_info['shop_id']],
                false
            );
        }


        //等待发货订单 发送消息
        if($order_status == "AWAITING_SHIPMENT"){
            // todo 消息数据推送到队列执行
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_PRIVATE_SEND_MESSAGE_QUEUE,
                [
                    'shop_id'        =>$order_info['shop_id'],
                    'order_id'       =>$order_info['order_id'],
                    'type'           =>1,
                    'text'           =>'',
                ],
                false
            );
        }


        //已交付订单发送消息
        if($order_status == "DELIVERED"){
            // todo 消息数据推送到队列执行
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_PRIVATE_SEND_MESSAGE_QUEUE,
                [
                    'shop_id'        =>$order_info['shop_id'],
                    'order_id'       =>$order_info['order_id'],
                    'type'           =>2,
                    'text'           =>'',
                ],
                false
            );
        }



    }


    /**
     * @desc 订单不存在时
     * @author luckyXiong
     * @date 2024-03-22
     */
    public function order_info_not_exist($order_id,$shop_id){
        htmlLog(['order_id'=>$order_id,'shop_id'=>$shop_id],OPERATE_LOG . date('Ym') . '/order_info_not_exist/' . date('Ymd') . '.txt');
        //投递存储消息的队列;
        MqTaskPushLogic::mq_task_push(
            '',
            MqQueueName::QUEUE_ORDER_INFO_OPERATE_QUEUE,
            ['order_id'=>$order_id,'shop_id'=>$shop_id],
            false
        );
    }



    /**
     * @desc   17track数据存储
     * @author zhangheng
     * @date   2024-05-29
     */
    public function webhooks_track($post)
    {

        htmlLog(['params'=>$post],OPERATE_LOG . date('Ym') . '/webhooks_track/' . date('Ymd') . '.txt');
        $number   = $post['data']['number']??'';
        if(empty($post['data']['track_info']) || !isset($post['data']['track_info'])){
              return '暂无track_info';
        }

        $track_info = $post['data']['track_info'];
        if(empty($track_info['tracking']['providers']) || !isset($track_info['tracking']['providers'])){
              return '暂无providers';
        }

        $providers = $track_info['tracking']['providers'][0] ?? [];
        if(empty($providers)){
            return '暂无providers';
        }

        $events = $providers['events'] ?? [];
        if(empty($events)){
            return '暂无events';
        }

        $exist_order = Db::name('order')->where('tracking_number',$number)->field('shop_id,order_id')->find();

        if(!$exist_order)  return '暂无物流单号';

        $row =  $insert_arr = [];
        foreach ($events as $event) {
            $row[] = [
                'order_id'         => $exist_order['order_id']??'',
                'shop_id'          => $exist_order['shop_id']??'',
                'tracking_number'  => $number,
                'time_iso'         => $event['time_iso'],
                'time_utc'         => $event['time_utc'],
                'time_number'      => md5($event['time_iso'].$number),
                'description'      => $event['description'],
                'location'         => $event['location'],
                'stage'            => $event['stage'],
                'sub_status'       => $event['sub_status']
            ];
        }


        if(!$row)   return '暂无数据';
        foreach($row as $v){
            $orderTrack = Db::name('order_track')->where('time_number', $v['time_number'])->value('id');
            if($orderTrack) continue;
            $insert_arr[] = $v;
        }

        if($insert_arr){
            Db::name('order_track')->insertAll($insert_arr);
        }
        return true;
    }


    /**
     * @desc  数据清洗生产
     * @author xx
     * @date 2024-07-10
     */
    public function shopifyChangePru(){
        $list =  Db::name('order_history_list')->field('id,order_id')->group('order_id')->select()->toArray();
        foreach($list as $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_TIK_ORDER_SHOPIFY_CHANGE_QUEUE,
                $v,
                false
            );
        }
    }





}